<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTb"></CategorySelect>
    </el-card>
    <!-- 展示属性值列表 -->
    <div v-show="isShowTb">
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="!category3Id"
        @click="addAttr"
        >添加属性</el-button
      >
      <el-card>
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column
            label="序号"
            width="82"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="attrName"
            label="属性名称"
            width="122"
          ></el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                v-for="value in row.attrValueList"
                :key="value.id"
                type="info"
                style="margin: 0 10px"
                >{{ value.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="222" align="center">
            <template slot-scope="{ row, $index }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="small"
                @click="editAttr(row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="deleteAttr(row, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 添加或编辑属性的结构 -->
    <div v-show="!isShowTb">
      <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
        <el-form-item label="属性名" style="margin-left: -20px">
          <el-input
            placeholder="请添加属性名"
            v-model="attrInfo.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="!attrInfo.attrName"
        @click="addAttrValue"
        >添加属性值</el-button
      >
      <el-table
        style="width: 50%; margin: 20px 0"
        border
        :data="attrInfo.attrValueList"
      >
        <el-table-column label="序号" width="80" align="center" type="index">
        </el-table-column>
        <!-- row是数组attrValueList的每一个对象 -->
        <el-table-column prop="prop" label="属性值名称" width="width">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.valueName"
              placeholder=""
              size="small"
              @blur="toSpan(row)"
              @keyup.native.enter="toSpan(row)"
              v-if="row.flag"
              ref="input"
            ></el-input>
            <span v-else @click="toEdit(row)" style="display: block">{{
              row.valueName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="288">
          <template slot-scope="{ row, $index }">
            <el-popconfirm
              :title="`你确定删除${row.valueName}吗`"
              @onConfirm="deleteAttrValue($index)"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                slot="reference"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="addOrEditAttr"
        :disabled="attrInfo.attrValueList.length < 1 || !checkValue"
        >保存</el-button
      >
      <el-button @click="isShowTb = true">取消</el-button>
    </div>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList: [],
      //是否显示表单
      isShowTb: true,
      //收集添加或编辑的属性和属性值 attrName：属性名，attrValueList装属性值(attrId：属性名id，valueName：属性值)，categoryId:三级分类的id
      attrInfo: {
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    // 通过子组件获取相应的id
    getCategoryId({ categoryId, level }) {
      if (level == 1) {
        this.category1Id = categoryId;
        this.category2Id = "";
        this.category3Id = "";
      } else if (level == 2) {
        this.category2Id = categoryId;
        this.category3Id = "";
      } else {
        this.category3Id = categoryId;
        this.getAttrList();
      }
    },
    //通过id获取属性和属性值
    async getAttrList() {
      let { category1Id, category2Id, category3Id } = this;
      let result = await this.$API.attr.reqGetAttrList(
        category1Id,
        category2Id,
        category3Id
      );
      if (result.code == 200) {
        this.attrList = result.data;
      }
    },
    //添加属性
    addAttr() {
      this.isShowTb = false;
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },
    //添加属性值,如果是编辑模式attrId就为原来属性名id，添加模式就为undefined
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: "",
        //标记查看模式和编辑模式
        flag: true,
      });
      this.$nextTick(() => this.$refs.input.focus());
    },
    //编辑已有的属性和值,给数组添加响应式数据flag
    editAttr(row) {
      this.isShowTb = false;
      this.attrInfo = cloneDeep(row);
      //标记查看模式和编辑模式
      this.attrInfo.attrValueList.forEach((item) =>
        this.$set(item, "flag", false)
      );
    },
    //不能输入空格和重复的属性值
    toSpan(row) {
      if (row.valueName.trim() == "") {
        this.$message.error("属性值不能为空");
        return;
      }
      //重复
      let a = this.attrInfo.attrValueList.find((item) => {
        if (item != row) {
          return item.valueName == row.valueName;
        }
      });
      if (a != undefined) {
        this.$message.error("属性值不能重复");
        row.valueName = "";
        return;
      }
      row.flag = false;
    },
    //到编辑模式，且聚焦
    toEdit(row) {
      row.flag = true;
      this.$nextTick(() => this.$refs.input.focus());
    },
    //删除属性值
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    // 保存发请求
    async addOrEditAttr() {
      this.attrInfo.attrValueList.forEach((item) => {
        delete item.flag;
      });
      try {
        await this.$API.attr.reqAddOrEditAttr(this.attrInfo);
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.isShowTb = true;
        this.getAttrList();
      } catch (error) {}
    },
    //删除属性
    async deleteAttr(row, index) {
      try {
        await this.$API.attr.reqDeleteAttr(row.id);
        this.getAttrList();
      } catch (error) {}
    },
  },
  computed: {
    checkValue() {
      let a = this.attrInfo.attrValueList.every((item) => {
        return item.valueName != "";
      });
      return a;
    },
  },
};
</script>

<style>
</style>